from fastapi import FastAPI,Request,Response
from exception import JsonException
from controller import user, ranking
from controller import test,question
from fastapi.responses import JSONResponse
from login.login import decode
from controller.rtn import Rtn
import logging
import uuid


# 配置日志
logging.basicConfig(
    filename="log/app.log",  # 指定日志文件的位置
    level=logging.WARN,  # 设置日志级别
    format='%(asctime)s - %(levelname)s - %(message)s',  # 日志格式
    encoding="utf-8"
)

logging.info("项目启动")

app = FastAPI()
app.include_router(question.router,prefix="/question")
app.include_router(test.router,prefix="/test")
app.include_router(user.router,prefix="/user")
app.include_router(ranking.router,prefix="/ranking")

# 权限验证中间件
@app.middleware("http")
async def auth(request: Request, call_next):

    # 跳过部分接口 start
    skip_path = [
        "/user/regist",
        "/api/user/regist",
    ]

    if request.url.path in skip_path:
        return  await call_next(request)
    
    # 跳过部分接口 end

    token = request.headers.get("Authorization")
    if(not token):
        token = ""

    token = token.replace("Bearer ","")
    try:
        userInfo = decode(token)
    except Exception as e:
        userInfo = JsonException("token decode 错误",401)

    if isinstance(userInfo, JsonException):
        return JSONResponse(
            status_code=userInfo.status_code,
            content={"errmsg": userInfo.detail},
            headers={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"*","Access-Control-Allow-Headers":"*","Access-Control-Allow-Credentials":"true"}
        )

    # if userInfo == None:
    #     return Response("鉴权失败", 401)
    # print("userInfo:",userInfo.__dict__)
    request.state.userInfo = userInfo
    response = await call_next(request)
    # response.headers["X-Process-Time"] = "hahaha"
    return response


# 重写异常处理
@app.exception_handler(JsonException)
async def http_exception_handler(req: Request, ex: JsonException):
    logging.warning(ex)
    return JSONResponse(
        status_code=ex.status_code,
        content = {
            "result": ex.status_code,
            "msg":ex.detail,
            "obj": ""
        },
        headers={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"*","Access-Control-Allow-Headers":"*","Access-Control-Allow-Credentials":"true"}
    )


# 重写全局异常处理
@app.exception_handler(Exception)
async def exception_handler(req: Request, ex: Exception):
    # print("@app.exception_handler(Exception)")
    logging.warning(ex)
    return JSONResponse(
        status_code=500,
        content={"errmsg": "发生错误"},
    )
